package com.thesis.client;

import java.util.ArrayList;
import java.util.Calendar;

import kankan.wheel.widget.OnWheelChangedListener;
import kankan.wheel.widget.WheelView;
import kankan.wheel.widget.adapters.NumericWheelAdapter;

import net.londatiga.android.ActionItem;
import net.londatiga.android.QuickAction;
import net.londatiga.android.QuickAction.OnActionItemClickListener;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.service.textservice.SpellCheckerService.Session;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;

import com.thesis.conectify.Connectify;
import com.thesis.object.Date;
import com.thesis.object.ListTable;
import com.thesis.object.Table;
import com.thesis.utils.Defines;
import com.thesis.utils.Utils;

public class TableMapActivity extends Activity {
	
	Calendar cal = Calendar.getInstance();

	int yy = cal.get(Calendar.YEAR);
	int mm = cal.get(Calendar.MONTH);
	int dd = cal.get(Calendar.DAY_OF_MONTH);
	
	private String booking_time;
	private String booking_des;
	ListTable listTable;
	ArrayList<Table> listTableActive;
	ArrayList<Integer> extra_table;
	int id_pick;
	int id_cancel_pick;
	int id_booking;
	GridView gridView;
	int fi_pos = 0;
	String user_name;
	
	AlertDialog levelDialog  ;
	int[] role ;
	@SuppressLint("ShowToast")
	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		role  = getIntent().getIntArrayExtra(Defines.USER_LOGIN_ROLE);
		new ListTableTask().execute();
		setContentView(R.layout.activity_table_map);
		setAlwaysShowActionOverflow(this);
		//-------------------------------
		
		//-------------------------------
		// user_name = getIntent().getStringExtra(Defines.USER_NAME);

		ActionItem pickItem = new ActionItem(Defines.QUICKACTION_PICK, getResources().getString(
				R.string.action_pick), getResources().getDrawable(
				R.drawable.icon_pick));
		ActionItem detailItem = new ActionItem(Defines.QUICKACTION_DETAIL, getResources().getString(
				R.string.action_detail), getResources()
				.getDrawable(R.drawable.icon_detail));
		ActionItem bookItem = new ActionItem(Defines.QUICKACTION_BOOK, getResources().getString(
				R.string.action_book), getResources()
				.getDrawable(R.drawable.icon_extra));
		ActionItem viewMenu = new ActionItem(Defines.QUICKACTION_MENU, getResources().getString(
				R.string.action_menu), getResources()
				.getDrawable(R.drawable.icon_menu));
		ActionItem bill = new ActionItem(Defines.QUICKACTION_BILL, getResources().getString(
				R.string.action_bill), getResources()
				.getDrawable(R.drawable.icon_menu));
		ActionItem cancel = new ActionItem(Defines.QUICKACTION_CANCELPICK,getResources().getString(
				R.string.action_cancelpick) , getResources()
				.getDrawable(R.drawable.icon_cancel));
		
	
		final QuickAction mQuickAction = new QuickAction(this);
		
			mQuickAction.addActionItem(pickItem);
			mQuickAction.addActionItem(detailItem);
			mQuickAction.addActionItem(bookItem);
		final QuickAction manageQuickAction = new QuickAction(this);
			manageQuickAction.addActionItem(detailItem);
			
		manageQuickAction.setOnActionItemClickListener(new OnActionItemClickListener() {
			
			@Override
			public void onItemClick(QuickAction source, int pos, int actionId) {
				// TODO Auto-generated method stub
				switch (actionId) {
				case Defines.QUICKACTION_DETAIL:
					Intent intent = new Intent(TableMapActivity.this,
							TableDetailActivity.class);
					String[] put = { listTable.getListTable().get(fi_pos).getTableName(),
							listTable.getListTable().get(fi_pos).getNumber()+"",
							listTable.getListTable().get(fi_pos).getDescription()
							};
					intent.putExtra(Defines.TABLE_DETAIL, put);
					startActivity(intent);
					break;

				default:
					break;
				}
			}
		});
	

		mQuickAction
				.setOnActionItemClickListener(new OnActionItemClickListener() {

					@Override
					public void onItemClick(QuickAction source, int pos,
							int actionId) {
						switch (actionId) {
						case Defines.QUICKACTION_PICK:
							listTableActive = Utils.sharedInstance().getListTableActive(listTable, role);
							for (int i = 0 ; i< listTableActive.size() ; i++){
								if (listTable.getListTable().get(fi_pos).getId() == 
										listTableActive.get(i).getId()){
									listTableActive.remove(i);
									break;
								}
									
							}
							CharSequence[] items = new CharSequence[listTableActive.size()];
							final boolean[]	items_check = new boolean[items.length];
								for (int i = 0 ; i< listTableActive.size(); i++){
									items[i] = listTableActive.get(i).getTableName();
								}

								
							   AlertDialog.Builder builder = new AlertDialog.Builder(TableMapActivity.this);
				                builder.setTitle("Bạn có muốn ghép với bàn nào khác không ?");
			                
				               builder.setMultiChoiceItems(items, items_check,new DialogInterface.OnMultiChoiceClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which,boolean isChecked) {
									// TODO Auto-generated method stub
									
								}
				            	   
				               });
				               builder.setPositiveButton("OK", new DialogInterface.OnClickListener(){

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									extra_table  = new ArrayList<Integer>();
									for (int i = 0 ; i< listTableActive.size();i++){
										if (items_check[i]){
											extra_table.add(listTableActive.get(i).getId());
											
										}
										id_pick = listTable.getListTable().get(fi_pos).getId();
									}
									for (int i = 0 ; i< extra_table.size();i++){
										Log.d("aaaa",""+extra_table.get(i));
									}
									new PickTable().execute();
									new ListTableTask().execute();
									levelDialog.dismiss();
									
								}
				            	   
				               } );
				                levelDialog = builder.create();
				                levelDialog.show();


							break;
						case Defines.QUICKACTION_DETAIL: {
							Intent intent = new Intent(TableMapActivity.this,
									TableDetailActivity.class);
							String[] put = { listTable.getListTable().get(fi_pos).getTableName(),
									listTable.getListTable().get(fi_pos).getNumber()+"",
									listTable.getListTable().get(fi_pos).getDescription()
									};
							intent.putExtra(Defines.TABLE_DETAIL, put);
							startActivity(intent);
						}
							break;
						case Defines.QUICKACTION_BOOK:
							TimepickBooking(TableMapActivity.this );
							
							break;
						default:
							break;

						}

					}

				});
		final QuickAction bQuickAction = new QuickAction(this);
		bQuickAction.addActionItem(viewMenu);
		bQuickAction.addActionItem(bill);
		bQuickAction.addActionItem(cancel);

		bQuickAction
				.setOnActionItemClickListener(new OnActionItemClickListener() {

					@Override
					public void onItemClick(QuickAction source, int pos,
							int actionId) {
						switch (actionId) {
						case Defines.QUICKACTION_MENU: {
							Intent intent = new Intent(TableMapActivity.this,
									MenuActivity.class);
							String[] put = {""+ role[1],listTable.getListTable().get(fi_pos).getTableName()};
							 intent.putExtra(Defines.ID_USER_TABLE_MENU, put);
							startActivity(intent);

						}
							break;

						case Defines.QUICKACTION_BILL:
							Intent in = new Intent(TableMapActivity.this,
									BillDetailTableActivity.class);
							String[] put = {""+ role[1],listTable.getListTable().get(fi_pos).getTableName()};
							in.putExtra(Defines.ID_TABLE_BILL_CUSTOMER, put);
							startActivity(in);
							break;
						case Defines.QUICKACTION_CANCELPICK:
							id_cancel_pick = listTable.getListTable().get(fi_pos).getId();
							new CancelPickTable().execute();
							new ListTableTask().execute();
							break;
						default:
							break;

						}

					}
				});
		gridView = (GridView) findViewById(R.id.gridView1);

		// String name_user = getIntent().getStringExtra(Defines.USER_NAME);
		// if (user_name.equals("user"))
		// gridView.setAdapter(new TableAdapter(this, table_user, check_user));
		// else gridView.setAdapter(new TableAdapter(this,
		// table_admin,check_admin));

		gridView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View v,
					int position, long id) {
				
				if ((role[0] == 0 && role[2] == listTable.getListTable().get(position).getManagerId())){
					if (listTable.getListTable().get(position).getStatusId() == 2)
					{
						fi_pos = position;
						bQuickAction.show(v);

					} else if (listTable.getListTable().get(position).getStatusId() == 1) {
						fi_pos = position;
						mQuickAction.show(v);
					} else {
						
					}
				} 
				else if  (role[0] == 2 && role[1] == listTable.getListTable().get(position).getManagerId()){
						fi_pos = position;
						manageQuickAction.show(v);
				}else {
					Utils.sharedInstance().showShortToast(TableMapActivity.this, getResources().getString(R.string.err_manage_table));
				}				
			}
		});
	}

	@Override
	protected void onResume() {
		new ListTableTask().execute();
		super.onResume();
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.table_map, menu);
		 if (role[0] == Defines.HIDE_MENU)
		    {
		        for (int i = 0; i < 3; i++)
		            menu.getItem(i).setVisible(false);
		    }
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		switch (item.getItemId()) {
		case R.id.action_viewmenu:
			startActivity(new Intent(TableMapActivity.this, MenuActivity.class));
			return true;
		case R.id.action_listnv:
			// if (user_name.equals("user"))
			// Toast.makeText(TableMapActivity.this, "Khu vực dành cho quản lý",
			// Toast.LENGTH_LONG);
			// else
			startActivity(new Intent(TableMapActivity.this, UserActivity.class));
			return true;

		case R.id.action_statistic:
			// if (user_name.equals("user"))
			// Toast.makeText(TableMapActivity.this, "Khu vực dành cho quản lý",
			// Toast.LENGTH_LONG);
			// else
			startActivity(new Intent(TableMapActivity.this,
					StatisticActivity.class));
			return true;
			
		case R.id.action_settings:	
			 startActivity(new Intent(TableMapActivity.this,SettingActivity.class));
			
			 return true;
		case R.id.action_refresh:
			new ListTableTask().execute();
			return true;
		case R.id.action_logout:
			
			
			new AlertDialog.Builder(TableMapActivity.this)
			.setTitle("Đăng xuất")
			.setMessage("Bạn có chắc chắn không ?")
			.setPositiveButton("Xác nhận", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					startActivity(new Intent(TableMapActivity.this,LoginActivity.class));
					finish();
				}
			})
			.setNegativeButton("Hủy",
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog,
								int which) {
							// TODO Auto-generated method stub
							return;
						}
					}).create().show();
			
			
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}

	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {

		menu.setGroupEnabled(R.menu.table_map, true);
		return super.onPrepareOptionsMenu(menu);
	}

	public void setAlwaysShowActionOverflow(Context context) {
		try {
			ViewConfiguration config = ViewConfiguration.get(context);
			java.lang.reflect.Field menuKeyField = ViewConfiguration.class
					.getDeclaredField("sHasPermanentMenuKey");
			if (menuKeyField != null) {
				menuKeyField.setAccessible(true);
				menuKeyField.setBoolean(config, false);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void TimepickBooking(final Context cons){
		LayoutInflater inf = LayoutInflater.from(cons);
		// layout of alert box contains
		View view = inf.inflate(R.layout.wheelbook, null);
		
		final EditText et_des = (EditText) view.findViewById(R.id.wb_et_desc);
		
		final WheelView hour = (WheelView) view.findViewById(R.id.hour);
		hour.setViewAdapter(new NumericWheelAdapter(cons, 00, 23));
		hour.setCyclic(false);
		
		final WheelView minute = (WheelView) view.findViewById(R.id.minute);
		minute.setViewAdapter(new NumericWheelAdapter(cons, 00, 59));
		minute.setCyclic(false);
		
		final WheelView month = (WheelView) view.findViewById(R.id.month);
		month.setViewAdapter(new NumericWheelAdapter(cons, 1, 12));
		month.setCyclic(false);

		final WheelView year = (WheelView) view.findViewById(R.id.year);
		year.setViewAdapter(new NumericWheelAdapter(cons, yy - 5, yy + 5));
		year.setCyclic(false);

		final WheelView date = (WheelView) view.findViewById(R.id.date);
		date.setViewAdapter(new NumericWheelAdapter(cons, 1, 31));
		date.setCyclic(false);
		
		OnWheelChangedListener changelistener_month = new OnWheelChangedListener() {

			@Override
			public void onChanged(WheelView wheel, int oldValue, int newValue) {
				// TODO Auto-generated method stub
				date.setViewAdapter(new NumericWheelAdapter(
						cons,
						1,
						dayOfmonth(newValue + 1, year.getCurrentItem() - 5 + yy)));
			}
		};
		OnWheelChangedListener changelistener_year = new OnWheelChangedListener() {

			@Override
			public void onChanged(WheelView wheel, int oldValue, int newValue) {
				// TODO Auto-generated method stub
				date.setViewAdapter(new NumericWheelAdapter(
						cons,
						1,
						dayOfmonth(month.getCurrentItem() + 1, newValue - 5 + yy)));
			}
		};
		
		hour.setCurrentItem(0);
		minute.setCurrentItem(0);
		
		date.setCurrentItem(dd - 1);
		month.setCurrentItem(mm);
		year.setCurrentItem(5);

		month.addChangingListener(changelistener_month);
		year.addChangingListener(changelistener_year);
		
		new AlertDialog.Builder(cons)
		.setMessage("Chọn thời gian")
		.setView(view)
		.setPositiveButton("Xác nhận", new DialogInterface.OnClickListener() {

			

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				// write code of lines, whatever want to with
				// value of this timepicker
				// hour value= hours.getCurrentItem();
				// minute value = mins.getCurrentItem();

//				tv_dayto.setText((new StringBuilder()
//						// Month is 0 based, just add 1
//						.append(date.getCurrentItem() + 1)
//						.append("-").append(month.getCurrentItem() + 1)
//						.append("-")
//						.append(year.getCurrentItem() - 5 + yy)).toString());
				Date dateEnd  = new Date(date.getCurrentItem() + 1,
						month.getCurrentItem() + 1, year.getCurrentItem() - 5 + yy);
				String h ;
				String m ;
				if(hour.getCurrentItem()>= 10) h = Integer.toString(hour.getCurrentItem());
				else h = "0"+Integer.toString(hour.getCurrentItem());
				
				if(hour.getCurrentItem()>= 10) m = Integer.toString(minute.getCurrentItem());
				else m = "0"+Integer.toString(minute.getCurrentItem());
				id_booking = listTable.getListTable().get(fi_pos).getId();
				booking_time = dateEnd.getStringdate()+" "+h+":"+m+":00";
				booking_des = et_des.getText().toString();
				
				new BookingTable().execute();
					
			}
		})
		.setNegativeButton("Hủy",
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog,
							int which) {
						// TODO Auto-generated method stub
						return;
					}
				}).create().show();
		
		
	}
	private int dayOfmonth(int month, int year) {
		if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8
				|| month == 10 || month == 12)
			return 31;
		else if (month == 4 || month == 6 || month == 9 || month == 11)
			return 30;
		else if (month == 2 && ((year % 4 == 0) && (year % 100 != 0))
				|| (year % 400 == 0))
			return 29;
		else
			return 28;
	}
	class ListTableTask extends AsyncTask<String, Void, Integer> {

		@Override
		protected Integer doInBackground(String... params) {
			// TODO Auto-generated method stub
			Connectify connect = new Connectify(TableMapActivity.this);
			listTable = new ListTable();
			listTable = connect.getAllTable();
			//Log.d("PHITEST",""+listTable.getListTable().size());
			return 0;
		}

		@Override
		protected void onPostExecute(Integer result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			
			
			
			gridView.setAdapter(new TableAdapter(TableMapActivity.this,
					listTable,role));

		}
	}
	class PickTable extends AsyncTask<String, String, String>{

		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub
			Connectify connect = new Connectify(TableMapActivity.this);
			connect.pickTable(id_pick, extra_table);
			return null;
		}
		
	}
	
	class CancelPickTable extends AsyncTask<String, String, String>{

		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub
			Connectify connect = new Connectify(TableMapActivity.this);
			connect.cancelPickTable(id_cancel_pick);
			return null;
		}
		
	}
	
	class BookingTable extends AsyncTask<String, String, String>{
		
		@Override
		protected void onPreExecute() {
			Log.d("booking itme", booking_time + booking_des);
			super.onPreExecute();
		}
		@Override
		protected String doInBackground(String... params) {
			Connectify connect = new Connectify(TableMapActivity.this);
			connect.bookingTable(id_booking, booking_time, booking_des);
			return null;
		}
		
	}
	
	
	
	
	

}